package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.adapter.PurSupplierListAdapter;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.component.MyListBottom;
import com.aoxon.cargo.component.MyRadioButton;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SearchSupplierFormCityMarkerService;
import com.aoxon.cargo.service.SearchSupplierService;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.reflect.TypeToken;

/**
 * 采购端供应商列表
 * 
 * @author ZZJ
 * 
 */
public class PurSupplierSearchShowActivity extends Activity implements
		MyRadioButton.OnCheckedListener, NormalDataLoader.OnLoadDataListener {

	private int visibleLastIndex;
	private int startIndex = 0;
	private int length = 20;
	private int loadType = 0;
	private boolean getFromText = true;
	private boolean isReachLast = false;

	private ImageView ivReturnButton;
	private ImageView ivGPSButton;

	private TextView tvTitle;

	private ListView lvSupplierList;

	private PurSupplierListAdapter adapter;

	private MyListBottom myListBottom;
	private MyRadioButton myRadioButton;

	private String searchText = "";
	private String city;
	private String market;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);
	
	private List<Supplier> suppliers = new ArrayList<Supplier>();

	private SearchSupplierService searchSupplierService = (SearchSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_SUPPLIER);
	private SearchSupplierFormCityMarkerService supplierFormCityMarkerService = (SearchSupplierFormCityMarkerService) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_SUPPLIER_FROM_CITYMARKET);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();

	}

	private void setup() {
		setContentView(R.layout.pur_supplier_list);
		
		View view = findViewById(R.id.sup_title);
		view.setVisibility(View.GONE);
		view = findViewById(R.id.pub_title);
		view.setVisibility(View.VISIBLE);
		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivGPSButton = (ImageView) findViewById(R.id.ivPublicTitleOther);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		lvSupplierList = (ListView) findViewById(R.id.lvPurSullierList);

		ivGPSButton.setVisibility(View.GONE);
		ivGPSButton.setImageResource(R.drawable.button_gps);

		myListBottom = new MyListBottom(this, lvSupplierList);
		myRadioButton = new MyRadioButton(this, "按人气排序", "按认证排序");
		myRadioButton.setOnCheckedChanged(this);

		adapter = new PurSupplierListAdapter(this, suppliers, false);
		lvSupplierList.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		lvSupplierList.setOnScrollListener(myScrollListener);
		lvSupplierList.setOnItemClickListener(myItemClickListener);

		normalDataLoader.setOnloadDataListener(this);
		
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();

		getFromText = bundle.getBoolean("searchFormText");

		if (getFromText) {

			searchText = bundle.getString("searchText");

			if (searchText != null) {
				tvTitle.setText(searchText);
			}

			loadType = 0;

		} else {

			city = bundle.getString("city");
			market = bundle.getString("market");

			if (market != null) {
				tvTitle.setText(market);
			}

			loadType = 2;

		}
		ivReturnButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PurSupplierSearchShowActivity.this.finish();
			}
		});

		normalDataLoader.load();

	}


	@Override
	public void checkOne() {
		// TODO Auto-generated method stub
		if (getFromText) {
			loadType = 0;
		} else {
			loadType = 2;
		}
		startIndex = 0;
		suppliers.clear();
		adapter.notifyDataSetChanged();
		normalDataLoader.load();
	}

	@Override
	public void checkTwo() {
		// TODO Auto-generated method stub
		if (getFromText) {
			loadType = 1;
		} else {
			loadType = 3;
		}
		startIndex = 0;
		suppliers.clear();
		adapter.notifyDataSetChanged();
		normalDataLoader.load();
	}

	OnScrollListener myScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				adapter.setBusy(true);
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				adapter.setBusy(false);
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				int lastIndex = adapter.getCount();
				adapter.setBusy(false);
				if (visibleLastIndex == lastIndex  && !isReachLast) {
					myListBottom.showProgressBar();
					myListBottom.setText("加载中～");
					normalDataLoader.load();
				}
				break;
			default:
				break;
			}
			adapter.notifyDataSetChanged();
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			visibleLastIndex = firstVisibleItem + visibleItemCount - 1;

		}
	};

	/**
	 * 选项点击监听
	 */
	OnItemClickListener myItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if ((adapter.getCount() != position)) {
				Intent intent = new Intent(PurSupplierSearchShowActivity.this,
						PurSupplierDetailsActivity.class);
				intent.putExtra("strSupplier",
						DataUtil.gson.toJson(suppliers.get(position)));
				startActivity(intent);
			}
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			return false;
		}
		return false;
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myListBottom.showProgressBar();
		myListBottom.setText("加载中...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		GsonBean gsonBean = null;

		switch (loadType) {
		case 0:
			gsonBean = searchSupplierService.execute(startIndex, length,
					searchText, true);
			Log.v("GsonBean", searchText);
			break;
		case 1:
			gsonBean = searchSupplierService.execute(startIndex, length,
					searchText, false);
			break;
		case 2:
			gsonBean = supplierFormCityMarkerService.execute(startIndex,
					length, true, city, market);
			break;
		case 3:
			gsonBean = supplierFormCityMarkerService.execute(startIndex,
					length, false, city, market);
			break;
		default:
			break;
		}

		if (CheckStateUtil.check(gsonBean)) {
			List<Supplier> supplierList = DataUtil.gson.fromJson(
					gsonBean.getStrJson(), new TypeToken<List<Supplier>>() {
					}.getType());
			startIndex += length;
			suppliers.addAll(supplierList);
			msg.what = MyStateUtil.LIST_CHANGE;
		} else {
			// 查找不到数据的情况
			isReachLast = true;
			msg.what = MyStateUtil.LIST_IS_REACH_LAST;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myListBottom.hideProgressBar();
		switch (state) {
		case MyStateUtil.LIST_CHANGE:
			Log.i("listChange",
					"------------------listChange--------------------");
			myListBottom.setText("向上拉加载数据");
			break;
		case MyStateUtil.LIST_IS_REACH_LAST:
			myListBottom.setText("没有相应数据咯～");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			myListBottom.setText("无网络连接～");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			myListBottom.setText("向上拉加载数据");
			ToastUtil.show(PurSupplierSearchShowActivity.this, "网络连接异常");
			break;
		default:
			break;
		}
		adapter.notifyDataSetChanged();
	}

}
